cd進專案目錄:
$composer require intervention/image
先在migration中建立儲存圖片url的欄位:
$table->string('image')->nullable();
model的$fillable[]也記得要加上'image'這個欄位。
table中建立好欄位後,進入你的專案,在config/app.php中$providers這個array裡加上:
Intervention\Image\ImageServiceProvider::class
在下面的$aliases這個array裡加上:
'Image' => Intervention\Image\Facades\Image::class
在專案目錄底下:
$php artisan storage:link
連結之後,project/storage/app/public 會跟 project/public/storage這兩個資料夾就回相連
use Intervention\Image\ImageManagerStatic as Image; //在檔案開頭的namespace加上
$request->validate([
'item' => ['required', 'unique:items'],
'image' => ['required', 'mimes:jpg,jpeg,bmp,png'],
]);
$parameters = request()->all();
if (request()->hasFile('image'))
{
// 檔案存在,所以存到project/storage/app/public,並拿到url,此範例會拿到public/fileName
$imageURL = request()->file('image')->store('public');
// 儲存純『檔名』到資料庫,因此把前面路徑修剪掉
$parameters['image'] = substr($imageURL, 7);
}
$create = Item::create([
'item' => $request['item'],
'image' => $parameters['image'],
]);
$result = $create->toArray();
if ($parameters['image'] != null){
$result['imageURL'] = asset('storage/' . $parameters['image']);
}
if ($create) {
return response()->json($result, 200);
}